package com.disease.api.service.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.disease.api.service.entity.DiseaseMapping;
import com.disease.api.service.mapper.DiseaseMappingMapper;
import com.disease.api.service.model.ResponseResult;
import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;


import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Service
public class DashBoardService {

    @Resource(name = "resourceJdbcTemplate")
    JdbcTemplate JdbcTemplate;

    @Autowired
    DiseaseMappingMapper diseaseMappingMapper;

    private List<DiseaseMapping> diseaseMappings;


    @PostConstruct
    public void init() {
        diseaseMappings = diseaseMappingMapper.select(new DiseaseMapping());
    }

    /**
     * 分类-传染病疾病统计汇总
     * @return
     */
    public ResponseResult diseaseTypeSummary(String startDate,String endDate){
        String sql = readSqlFile("/sql/diseaseTypeSummary.sql");
        sql = sql.replace("${start_date}",startDate).replace("${end_date}",endDate);
        ResponseResult responseResult = executeJdbcTemplate(sql);
        if(responseResult.isSuccess()){
            List<Map<String,String>> result =(List<Map<String,String>>) responseResult.getData();
            for (Map<String, String> response : result) {
                String thirdname = response.get("thirdname");
                Optional<DiseaseMapping> diseaseNameMatchOptional = diseaseMappings.stream().filter(diseaseMapping -> diseaseMapping.getThirdLevel().equals(thirdname)).findFirst();
                if(diseaseNameMatchOptional.isPresent()){
                    response.put("secondname", Optional.ofNullable(diseaseNameMatchOptional.get().getSecondLevel()).orElse("其他"));
                    response.put("firstname",diseaseNameMatchOptional.get().getFirstLevel());
                }else{
                    response.put("secondname","其他");
                    response.put("firstname","其他");
                }
            }
        }
        return responseResult;
    }

    /**
     * 分类-传染病疾病统计汇总
     * @return
     */
    public ResponseResult diseaseItemByType(String startDate,String endDate){
        String sql = readSqlFile("/sql/diseaseItemByType.sql");
        sql = sql.replace("${start_date}",startDate).replace("${end_date}",endDate);
        ResponseResult responseResult = executeJdbcTemplate(sql);
        if(responseResult.isSuccess()){
            List<Map<String,String>> result =(List<Map<String,String>>) responseResult.getData();
            for (Map<String, String> response : result) {
                String thirdname = response.get("thirdname");
                Optional<DiseaseMapping> diseaseNameMatchOptional = diseaseMappings.stream().filter(diseaseMapping -> diseaseMapping.getThirdLevel().equals(thirdname)).findFirst();
                if(diseaseNameMatchOptional.isPresent()){
                    response.put("secondname", Optional.ofNullable(diseaseNameMatchOptional.get().getSecondLevel()).orElse("其他"));
                    response.put("firstname",diseaseNameMatchOptional.get().getFirstLevel());
                }else{
                    response.put("secondname","其他");
                    response.put("firstname","其他");
                }
            }
        }
        return responseResult;
    }

    /**
     * 科室-传染病报告统计汇总
     * @param startDate
     * @param endDate
     * @return
     */
    public ResponseResult diseaseDepartmentSummary(String startDate,String endDate){
        String sql = readSqlFile("sql/diseaseDepartmentSummary.sql");
        sql = sql.replace("${start_date}",startDate).replace("${end_date}",endDate);
        return executeJdbcTemplate(sql);
    }

    /**
     * 医生-传染病报告统计明细
     * @param startDate
     * @param endDate
     * @return
     */
    public ResponseResult diseaseItemByDepartment(String startDate,String endDate){
        String sql = readSqlFile("sql/diseaseItemByDepartment.sql");
        sql = sql.replace("${start_date}",startDate).replace("${end_date}",endDate);
        return executeJdbcTemplate(sql);
    }

    /**
     * 医生-传染病报告统计明细
     * @param startDate
     * @param endDate
     * @return
     */
    public ResponseResult diseaseItemByDoctor(String startDate,String endDate){
        String sql = readSqlFile("sql/diseaseItemByDoctor.sql");
        sql = sql.replace("${start_date}",startDate).replace("${end_date}",endDate);
        return executeJdbcTemplate(sql);
    }

    public String readSqlFile(String filePath){
        // 确保路径以"/"开头
        if (!filePath.startsWith("/")) {
            filePath = "/" + filePath;
        }

        try (InputStream inputStream = getClass().getResourceAsStream(filePath)) {
            if (inputStream == null) {
                log.error("文件不存在: {}", filePath);
                return "";
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            return content.toString();
        } catch (Exception e) {
            log.error("读取文件失败: {}, 错误: {}", filePath, e.getMessage());
            return "";
        }
    }

    private ResponseResult executeJdbcTemplate(String sql){
        if(StringUtils.isBlank(sql)) return ResponseResult.fail("查询失败,sql为空");
        try {
            return ResponseResult.success(JdbcTemplate.queryForList(sql));
        }catch (Exception e){
            log.error("executeJdbcTemplate查询失败:{}",e.getMessage());
            return ResponseResult.fail("查询失败");
        }
    }
}
